package dao;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.sql.Connection;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.TreeSet;

import model.ModelBase;

@SuppressWarnings("deprecation")
public abstract class AbstractRecordDAO<T> implements DAO<T> 
{

  protected SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");

  /**
   * You have to close the provided <code>InputStream<code> in by yourself!
   */
  @Override
  public T read(InputStream in) throws IOException 
  {
    DataInputStream dis = new DataInputStream(new BufferedInputStream(in));
    return parse(dis.readLine());
  }

  /**
   * You have to close the provided <code>InputStream<code> in by yourself!
   */
  @Override
  public Collection<T> readMultiple(InputStream in) throws IOException 
  {
    Collection<T> data = new TreeSet<T>();
    DataInputStream dis = new DataInputStream(new BufferedInputStream(in));
    String line = dis.readUTF();
    while (line != null) 
    {
      data.add(parse(line));
      line = dis.readUTF();
    }
    return data;
  }

  /**
   * You have to close the provided <code>InputStream<code> in by yourself!
   */
  @Override
  public void write(OutputStream out, T data) throws IOException 
  {
    PrintWriter writer = new PrintWriter(new BufferedOutputStream(out));
    writer.println(build(data));
    writer.flush();
  }

  /**
   * You have to close the provided <code>InputStream<code> in by yourself!
   */
  @Override
  public void writeMultiple(OutputStream out, Collection<T> data) throws IOException 
  {
    PrintWriter writer = new PrintWriter(new BufferedOutputStream(out));
    for (T model : data) 
    {
      writer.write(build(model));
    }
    writer.flush();
  }

  protected abstract T parse(String line);

  protected abstract String build(T model);
  
	@Override
	public int delete(Connection connection, ModelBase data)
	{
		return 0;
	}
	
	@Override
	public int save(Connection connection, ModelBase data)
	{
		return 0;
	}
}